package xyz.bernkastel.goods_in_great_demand.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.bernkastel.goods_in_great_demand.common.CustomException;
import xyz.bernkastel.goods_in_great_demand.common.R;
import xyz.bernkastel.goods_in_great_demand.dto.GoodsDto;
import xyz.bernkastel.goods_in_great_demand.entity.Category;
import xyz.bernkastel.goods_in_great_demand.entity.Goods;
import xyz.bernkastel.goods_in_great_demand.entity.GoodsTag;
import xyz.bernkastel.goods_in_great_demand.service.CategoryService;
import xyz.bernkastel.goods_in_great_demand.service.GoodsService;
import xyz.bernkastel.goods_in_great_demand.service.GoodsTagService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品管理
 */
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsTagService goodsTagService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增商品
     *
     * @param goodsDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody GoodsDto goodsDto) {
        log.info(goodsDto.toString());

        goodsService.saveWithTag(goodsDto);
        return R.success("新增商品成功");
    }

    /**
     * 商品信息分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Goods> pageInfo = new Page<>(page, pageSize);
        Page<GoodsDto> goodsDtoPage = new Page<>();
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();

        //过滤条件
        queryWrapper.like(name != null, Goods::getName, name);
        queryWrapper.orderByDesc(Goods::getUpdateTime);

        //执行分页查询
        goodsService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, goodsDtoPage, "records");
        List<Goods> records = pageInfo.getRecords();
        List<GoodsDto> list = records.stream().map((item) -> {
            GoodsDto goodsDto = new GoodsDto();
            BeanUtils.copyProperties(item, goodsDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                goodsDto.setCategoryName(categoryName);
            }
            return goodsDto;
        }).collect(Collectors.toList());
        goodsDtoPage.setRecords(list);
        return R.success(goodsDtoPage);
    }

    /**
     * 根据id查询商品及其标签
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<GoodsDto> get(@PathVariable Long id) {
        GoodsDto goodsDto = goodsService.getByIdWithTag(id);
        return R.success(goodsDto);
    }

    /**
     * 修改商品
     *
     * @param goodsDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody GoodsDto goodsDto) {
        log.info(goodsDto.toString());

        goodsService.updateWithTag(goodsDto);
        return R.success("修改商品成功");
    }

    /**
     * 根据条件查询对应商品
     *
     * @param goods
     * @return
     */
    @GetMapping("/list")
    public R<List<GoodsDto>> list(Goods goods) {
        //构造查询条件
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(goods.getCategoryId() != null, Goods::getCategoryId, goods.getCategoryId());
        queryWrapper.orderByAsc(Goods::getSort).orderByDesc(Goods::getUpdateTime);


        List<Goods> list = goodsService.list(queryWrapper);
        List<GoodsDto> dtoList = list.stream().map((item) -> {
            GoodsDto goodsDto = new GoodsDto();
            BeanUtils.copyProperties(item, goodsDto);
            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                goodsDto.setCategoryName(categoryName);
            }

            //当前商品id
            Long goodsId = item.getId();
            LambdaQueryWrapper<GoodsTag> goodsTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsTagLambdaQueryWrapper.eq(GoodsTag::getGoodsId, goodsId);
            List<GoodsTag> goodsTags = goodsTagService.list(goodsTagLambdaQueryWrapper);

            goodsDto.setTags(goodsTags);
            return goodsDto;
        }).collect(Collectors.toList());

        return R.success(dtoList);
    }

    /**
     * 修改售卖状态（起售，停售）
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> statusWithIds(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        //构造一个条件构造器
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Goods::getId, ids);
        queryWrapper.orderByDesc(Goods::getPrice);
        //根据条件进行批量查询
        List<Goods> list = goodsService.list(queryWrapper);
        for (Goods goods : list) {
            if (goods != null) {
                //把浏览器传入的status参数赋值商品
                goods.setStatus(status);
                goodsService.updateById(goods);
            }
        }
        return R.success("状态修改成功");
    }

    /**
     * 批量删除商品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam List<Long> ids) {
        //构造一个条件构造器
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Goods::getId, ids);
        List<Goods> list = goodsService.list(queryWrapper);
        for (Goods goods : list) {
            if (goods.getStatus() == 0) {
                //停售状态直接删除
                goodsService.removeById(goods.getId());
                LambdaQueryWrapper<GoodsTag> goodsFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                goodsFlavorLambdaQueryWrapper.eq(GoodsTag::getGoodsId, goods.getId());
                goodsTagService.remove(goodsFlavorLambdaQueryWrapper);
            } else {
                throw new CustomException("此商品还在售卖阶段，无法删除！");
            }
        }
        return R.success("删除成功");
    }


}
